<?php

namespace app\mini\controller;

use app\common\controller\ApiController;
use app\common\model\Dealer;
use app\common\model\Driver;
use app\mini\model\Salesman;
use app\common\service\easysms\EasySmsService;
use app\common\validate\LoginValidate;
use app\common\enum\mini\Login as LoginEnum;
use app\Request;
use think\App;
use think\facade\Cache;
use think\response\Json;


class Login extends ApiController
{
    protected bool $ignoreAuth = true;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->validateClass = LoginValidate::class;
    }

    /**
     * 小程序登录
     */
    public function login(Request $request): Json
    {
        $post = $request->post();
        $this->sceneValidate($post, 'wx_login');
        // 判断登录端
        switch ($post['scene_id']){
            case LoginEnum::DEALER:
                $sceneText = '经销商';
                $this->model = new Dealer();
                $sql = $this->model->field('id,name,company_id,phone,password,status,logo')->with([
                    'company' => function ($query) {
                        $query->field('id,name');
                    }
                ]);
                break;
            case LoginEnum::SALESMAN:
                $sceneText = '业务员';
                $this->model = new Salesman();
                $sql = $this->model->field('id,`rename` as `name`,company_id,phone,password,status,job_status,head_img')->with([
                        'company' => function ($query) {
                            $query->field('id,name');
                        }
                    ]);
                break;
            case LoginEnum::DRIVER:
                $sceneText = '司机';
                $this->model = new Driver();
                $sql = $this->model->field('id,name,company_id,phone,password,status')->with([
                        'company' => function ($query) {
                            $query->field('id,name');
                        }
                    ]);
                break;
            default:
                $sceneText = '';
                return $this->error('非法请求');
        }
        $userInfo = $sql->where(['phone' => $post['phone']])->find();
        if (empty($userInfo)) {
            return $this->error('用户不存在');
        }
        if(!empty($post['sms_code'])){
            $smsCode = Cache::get($post['phone']);
            if($smsCode != $post['sms_code']){
                return $this->error('验证码有误');
            }
        }else if (empty($post['password']) || password($post['password']) != $userInfo->password) {
            return $this->error('密码输入有误');
        }
        if($userInfo->status == 2){
            return $this->error('账号已被禁用');
        }
        if($post['scene_id'] == LoginEnum::SALESMAN && $userInfo->job_status == 2){
            return $this->error('该业务员已离职，请管理员核对后再登录！');
        }
//        $this->userInfo->login_num       += 1;
//        $this->userInfo->last_login_ip   = $request->ip();
//        $this->userInfo->last_login_time = time();
//        $this->userInfo->save();
        $this->userInfo = $userInfo->toArray();
        $this->userInfo['scene_id'] = $post['scene_id'];
        $token = $this->getToken($post['scene_id']);
        Cache::tag('cache_wx')->set($token, $this->userInfo, 86400 * 7);
        return $this->success(['token' => $token,'user_info'=>$this->userInfo,'scene_id'=>$post['scene_id'],'scene_text'=>$sceneText], '登录成功');
    }

    /**
     * 获取token
     * @param $sceneId
     * @return string
     */
    private function getToken($sceneId): string
    {
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        $salt = 'wx_token_api';
        return sha1(md5("{$sceneId}_{$timeStamp}_{$salt}"));
    }

    /**
     * 发送短信
     * @param $phone
     * @return Json
     */
    public function sendSms($phone): Json
    {
        // EasySms服务类
        $res = EasySmsService::getInstance()->sendSms($phone);
        return $this->success($res);
    }
}